<template>
  <div class="edit-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? '编辑药材' : '新增药材' }}</span>
          <el-button @click="router.back()">返回</el-button>
        </div>
      </template>

      <el-form
          :model="form"
          :rules="rules"
          ref="formRef"
          label-width="120px"
          style="max-width: 800px;"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="药材名称" prop="herbName">
              <el-input v-model="form.herbName" placeholder="请输入药材名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="拼音名称" prop="pinyinName">
              <el-input v-model="form.pinyinName" placeholder="请输入拼音名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="拉丁学名" prop="latinName">
              <el-input v-model="form.latinName" placeholder="请输入拉丁学名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类" prop="categoryId">
              <el-select
                  v-model="form.categoryId"
                  placeholder="请选择分类"
                  style="width: 100%"
                  filterable
              >
                <el-option
                    v-for="category in categoryList"
                    :key="category.categoryId"
                    :label="category.categoryName"
                    :value="category.categoryId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="药用部位" prop="partUsed">
              <el-select
                  v-model="form.partUsed"
                  placeholder="请选择药用部位"
                  style="width: 100%"
              >
                <el-option label="根" value="root" />
                <el-option label="叶" value="leaf" />
                <el-option label="花" value="flower" />
                <el-option label="果实" value="fruit" />
                <el-option label="种子" value="seed" />
                <el-option label="树皮" value="bark" />
                <el-option label="全草" value="whole_plant" />
                <el-option label="根茎" value="rhizome" />
                <el-option label="鳞茎" value="bulb" />
                <el-option label="菌核" value="fungus" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性" prop="nature">
              <el-select
                  v-model="form.nature"
                  placeholder="请选择性"
                  style="width: 100%"
              >
                <el-option label="寒" value="cold" />
                <el-option label="凉" value="cool" />
                <el-option label="平" value="neutral" />
                <el-option label="温" value="warm" />
                <el-option label="热" value="hot" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="味" prop="taste">
              <el-input v-model="form.taste" placeholder="请输入味，多个用逗号分隔" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归经" prop="meridianTropism">
              <el-input v-model="form.meridianTropism" placeholder="请输入归经" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="描述" prop="description">
          <el-input
              v-model="form.description"
              type="textarea"
              :rows="3"
              placeholder="请输入药材描述"
          />
        </el-form-item>

        <el-form-item label="功效" prop="functions">
          <el-input
              v-model="form.functions"
              type="textarea"
              :rows="3"
              placeholder="请输入功效"
          />
        </el-form-item>

        <el-form-item label="主治" prop="indications">
          <el-input
              v-model="form.indications"
              type="textarea"
              :rows="3"
              placeholder="请输入主治"
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用法用量" prop="dosageGuidance">
              <el-input
                  v-model="form.dosageGuidance"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入用法用量"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="禁忌" prop="contraindications">
              <el-input
                  v-model="form.contraindications"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入禁忌"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="炮制方法" prop="processingMethods">
          <el-input
              v-model="form.processingMethods"
              type="textarea"
              :rows="2"
              placeholder="请输入炮制方法"
          />
        </el-form-item>

        <el-form-item label="贮藏条件" prop="storageConditions">
          <el-input
              v-model="form.storageConditions"
              type="textarea"
              :rows="2"
              placeholder="请输入贮藏条件"
          />
        </el-form-item>

        <el-form-item label="质量标准" prop="qualityStandards">
          <el-input
              v-model="form.qualityStandards"
              type="textarea"
              :rows="2"
              placeholder="请输入质量标准"
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否有毒" prop="isToxic">
              <el-switch v-model="form.isToxic" />
              <span style="margin-left: 10px;">{{ form.isToxic ? '是' : '否' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="毒性等级" prop="toxicityLevel" v-if="form.isToxic">
              <el-select
                  v-model="form.toxicityLevel"
                  placeholder="请选择毒性等级"
                  style="width: 100%"
              >
                <el-option label="无" value="none" />
                <el-option label="低毒" value="low" />
                <el-option label="中毒" value="medium" />
                <el-option label="高毒" value="high" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="available">启用</el-radio>
            <el-radio label="unavailable">禁用</el-radio>
            <el-radio label="restricted">限制</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
          <el-button @click="router.back()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { chineseHerbApi, herbCategoryApi } from '@/api/admin'

const route = useRoute()
const router = useRouter()
const formRef = ref()
const loading = ref(false)
const categoryList = ref([])

console.log('=== 中药材编辑页面初始化 ===')
console.log('路由参数:', route.params)
console.log('路由查询:', route.query)

// 注意：路由配置中参数是 :herbId，所以这里要用 route.params.herbId
const isEdit = computed(() => route.params.herbId !== undefined)

const form = reactive({
  herbId: null,
  herbName: '',
  pinyinName: '',
  latinName: '',
  categoryId: null,
  partUsed: '',
  nature: '',
  taste: '',
  meridianTropism: '',
  description: '',
  functions: '',
  indications: '',
  dosageGuidance: '',
  contraindications: '',
  processingMethods: '',
  storageConditions: '',
  qualityStandards: '',
  isToxic: false,
  toxicityLevel: 'none',
  status: 'available'
})

const rules = {
  herbName: [
    { required: true, message: '请输入药材名称', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  partUsed: [
    { required: true, message: '请选择药用部位', trigger: 'change' }
  ],
  nature: [
    { required: true, message: '请选择性', trigger: 'change' }
  ],
  functions: [
    { required: true, message: '请输入功效', trigger: 'blur' }
  ]
}

const loadCategories = async () => {
  try {
    console.log('开始加载分类列表...')
    const res = await herbCategoryApi.getTree()
    console.log('分类API返回:', res.data)

    const flattenCategories = (categories) => {
      let result = []
      categories.forEach(cat => {
        result.push({
          categoryId: cat.categoryId,
          categoryName: cat.categoryName
        })
        if (cat.children) {
          result = result.concat(flattenCategories(cat.children))
        }
      })
      return result
    }
    categoryList.value = flattenCategories(res.data || [])
    console.log('分类列表加载完成:', categoryList.value)
  } catch (error) {
    console.error('加载分类失败:', error)
    ElMessage.error('加载分类失败')
  }
}

const loadHerbDetail = async (id) => {
  console.log('开始加载药材详情，ID:', id)
  try {
    const res = await chineseHerbApi.getById(id)
    console.log('药材详情API返回:', res.data)

    if (!res.data) {
      ElMessage.error('未找到对应的药材记录')
      router.back()
      return
    }

    // 清空表单然后重新赋值
    Object.keys(form).forEach(key => {
      if (key in res.data) {
        form[key] = res.data[key]
      }
    })

    console.log('表单数据赋值完成:', form)
    ElMessage.success('药材详情加载成功')
  } catch (error) {
    console.error('加载药材详情失败:', error)
    ElMessage.error('加载药材详情失败')
    router.back()
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (!valid) return

    loading.value = true
    try {
      if (isEdit.value) {
        console.log('更新药材:', form)
        await chineseHerbApi.update(form)
        ElMessage.success('更新成功')
      } else {
        console.log('新增药材:', form)
        await chineseHerbApi.add(form)
        ElMessage.success('创建成功')
      }
      router.push('/admin/chinese-herb')
    } catch (error) {
      console.error('操作失败:', error)
      ElMessage.error('操作失败: ' + (error.message || '未知错误'))
    } finally {
      loading.value = false
    }
  })
}

// 监听路由参数变化
watch(() => route.params.herbId, (newId) => {
  if (newId && isEdit.value) {
    console.log('路由参数变化，重新加载数据:', newId)
    loadHerbDetail(newId)
  }
})

onMounted(() => {
  console.log('编辑页面 mounted, herbId:', route.params.herbId)

  loadCategories()

  if (isEdit.value) {
    loadHerbDetail(route.params.herbId)
  }
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.edit-container {
  padding: 20px;
}
</style>
